import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		finance: {},
		userinfo: {},
		token: '',
		ws: {},
		version: '',
		name: '',
		city: {},
		url: 'http://v2.qidka.com',
		upload: 'http://v2.qidka.com/api/upload/image'
	},
	mutations: {
		// token => vuex
		setToken(state, token) {
			if (token) {
				state.token = token
				uni.setStorageSync('token', token)
			} else {
				let tmp = uni.getStorageSync('token')
				tmp && this.commit('setToken', tmp)
			}
		},
		// userinfo => vuex
		userLogin(state, user) {
			if (user) {
				state.userinfo = user
				uni.setStorageSync('userinfo', JSON.stringify(user))
			} else {
				let tmp = uni.getStorageSync('userinfo')
				tmp && this.commit('userLogin', JSON.parse(tmp))
			}
		},
		// finance => vuex
		setFinance(state, info) {
			state.finance = info
		},
		clearFinance(state) {
			state.finance = ''
		},
		// vuex clear
		userLogout(state) {
			state.userinfo = ''
			state.token = ''
			uni.removeStorageSync('userinfo')
			uni.removeStorageSync('token')
			this.commit('clearFinance')
		},
		wsInit(state) {
			let ws = uni.connectSocket({
				url: 'wss://www.qidka.com/websocket',
				complete: () => {}
			});
			ws.onOpen(res => {
				console.log('open', res)
			})
			ws.onMessage(res => {
				console.log('msg', res)
			})
			ws.onError(res => {
				console.log('error', res)
			})
		},
		// 检查更新
		getVer(state, cb) {
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, info => {
				state.version = info.version
				state.name = info.name
				if (cb) {
					cb();
				}
			});
			// #endif
		},
		// 缓存city
		setCity(state, city) {
			state.city = city
			uni.setStorageSync('city', JSON.stringify(city))
		},
		// 读取city
		getCity(state) {
			let citystr = uni.getStorageSync('city')
			if (citystr) {
				let city = JSON.parse(citystr)
				this.commit('setCity', city)
			}
		}
	}
})

export default store
